package com.zbw.weightlibrary.Connector;
import android.util.Log;

import com.zbw.weightlibrary.Util.ThreadPoolManager;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018-12-11.
 */

public abstract class BaseControlImpl implements IBleControl {
    //添加公共参数、功能等
    public DecimalFormat decimalFormat = new DecimalFormat("0.000");
    private IinfoCallback mCallback;
    protected boolean ReadWeight;//是否读取重量
    protected ArrayList<byte[]> mRecvData;
    List<String> dataStr = new ArrayList<>();
    protected int ValueSize;
    private List<Integer> sizeList;

    public BaseControlImpl(IinfoCallback callback) {
        mCallback = callback;
    }

    protected void ReadWeight(final InputStream inputStream){
        ReadWeight = true;
        mRecvData = new ArrayList<>();
        ValueSize = 0;
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                try {
                    byte[] data = new byte[128];
                    int size;
                    while (inputStream != null && ReadWeight) {
                        if (inputStream.available() > 0) {
                            size = inputStream.read(data);
                            if (size > 0) {
                                ByteBuffer bb = ByteBuffer.allocate(size);
                                bb.put(data, 0, size);
                                postOnReceived(bb.array());
                            } else {
                                break;
                            }
                        } else {
                            Thread.sleep(100);
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    mCallback.onGetWeight("获取重量失败！"+e.getMessage(),false);
                }
            }
        });
    }

    protected void postOnReceived(byte[] data) {
        synchronized (mRecvData) {
            mRecvData.add(data);
            while (countByteArrayList(mRecvData) > 1024)
                mRecvData.remove(0);

            String str = null;
            synchronized (mRecvData) {
                for (byte[] d : mRecvData) {
                    str = new String(d);
                }
            }
            if(str!=null) {
                CutOutString(str);
            }
        }
    }

    //重量数据解析后返回
    protected  void CutOutString(String value) {
        value = filterUnNumber(value);
        //Log.i("正则数据", value);
        int size = value.length();

        if(ValueSize==0&&size < 10){
            AssignmentValueSize(value);
        }

        if (size < 10 && size >= 4) {
            if(ValueSize==0||size==ValueSize||isDaHua(value)||value.startsWith("-")){
                if(value.startsWith(".")||value.endsWith(".")){
                    return;
                }
                //Log.i("过滤之后", value);
                //连续三次返回值相同判为稳定，否则判为不稳定
                int Status = 0;
                dataStr.add(0, value);
                if (dataStr.size() == 4) {
                    dataStr.remove(3);
                }
                if (dataStr.size() == 3) {
                    if (dataStr.get(0).equals(dataStr.get(1)) && dataStr.get(0).equals(dataStr.get(2))) {
                        Status = 1;
                    } else {
                        Status = 0;
                    }
                }
                try {
                    //这个地方写的不是很好，效率低下，每次都要正则求证是否是大华电子秤格式
                    if(isDaHua(value)){
                        value = decimalFormat.format(Double.parseDouble(value)*0.001);
                    }else{
                        value = decimalFormat.format(Double.valueOf(value));
                    }
                    mCallback.onGetWeight(value, Status == 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static int countByteArrayList(ArrayList<byte[]> data) {
        int size = 0;
        for (byte[] d : data)
            size += d.length;
        return size;
    }

    /**
     * 匹配大华电子秤
     * 大华电子秤没有小数点，而且不稳定的时候，不会返回
     * 返回长度为 4或者5位
     * 返回格式 0160 = 0.160   1160 = 1.160   11200 = 11.200
     * @return
     */
    private boolean isDaHua(String value){
        //只匹配数字，没有小数点，长度为4或者5,并且计算的目标长度必须是4或者5
        return value.matches("^[0-9]{4,5}");
    }


    /**
     * 计算目标字符串正常长度
     * @param value
     */
    private void AssignmentValueSize(String value){
        //Log.i("value_Ass",value);
        if(sizeList==null){
            sizeList = new ArrayList<>();
        }
        sizeList.add(value.length());
        if(sizeList.size()>=10){
            if(sizeList.get(0).equals(sizeList.get(1)) &&
                    sizeList.get(0).equals(sizeList.get(2))&&
                    sizeList.get(0).equals(sizeList.get(3))&&
                    sizeList.get(0).equals(sizeList.get(4))&&
                    sizeList.get(0).equals(sizeList.get(5))&&
                    sizeList.get(0).equals(sizeList.get(6))&&
                    sizeList.get(0).equals(sizeList.get(7))&&
                    sizeList.get(0).equals(sizeList.get(8))&&
                    sizeList.get(0).equals(sizeList.get(9))){
                ValueSize = sizeList.get(0);
            }else{
                sizeList.removeAll(sizeList);
            }
        }
    }

    /**
     *
     * @param str
     *         需要过滤的字符串
     * @return
     * @Description:过滤数字以外的字符
     */
    public static String filterUnNumber(String str) {
        // 只允数字
        String regEx = "[^0-9\\.\\-]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        //替换与模式匹配的所有字符（即非数字的字符将被""替换）
        return m.replaceAll("").trim();
    }
}
